package com.dirtylily.myblog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class logAspect {
//拿到日志信息

private final Logger logger = LoggerFactory.getLogger(this.getClass());

//声明log是一个切面，每回访问controller都会经过这么个切面
@Pointcut("execution(* com.dirtylily.myblog.controller.*.*(..))")
public void log(){

}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
    logger.info("===========before==========");
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //获取URL、IP
    String url = request.getRequestURL().toString();
    String ip = request.getRemoteAddr();
    //获取请求方法
    String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    //获取请求参数
    Object[] args = joinPoint.getArgs();
    RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
    logger.info("Request : {}", requestLog);
}

@After("log()")
public void doAfter(){
    logger.info("===========after===========");
}

@AfterReturning(returning = "result",pointcut = "log()")
public void doAfterReturn(Object result){
    logger.info("Result : {}", result);
}

//封装参数
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
